<template>
  <Dialog v-model="dialogVisible" title="账号授权" width="430px">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="rules" label-width="100">
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username" :maxlength="50" placeholder="请输入账号" class="!w-230px" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" :show-password="true" :maxlength="50" placeholder="请输入密码"
          class="!w-230px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">验证并授权</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import * as authorizationManageApi from '@/api/authorizationManage'

  const emit = defineEmits(['success'])
  const message = useMessage()
  const formRef = ref()
  const formLoading = ref(false)
  const dialogVisible = ref(false)

  const formData = ref({
    username: undefined,
    password: undefined
  })

  const rules = reactive({
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  })

  const open = async () => {
    resetFn()
    dialogVisible.value = true
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    try {
      formLoading.value = true
      await authorizationManageApi.accountAuthorize(formData.value)
      message.success('账号授权成功')
      emit('success')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }

  const resetFn = () => {
    formData.value = {
      username: undefined,
      password: undefined
    }
    formRef.value?.resetFields()
  }

  defineExpose({ open })
</script>
<style lang="scss" scoped>
</style>